var map = null;
var geocoder = null;
var highlighted_marker = null;
var point_markers = [];
var directionsPanel;
var directions;
var polyline;

//initialize ctmapv2
function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        var center = new GLatLng(48.85884228699207,2.341461181640625);
        map.setCenter(center, 13);
        var userNames =['lizhi','shiyi','peiyu','xiaojiao','weijiao','yuwei'];
        var userIcons = [ 'image/lizhi.png', 'image/shiyi.png', 'image/peiyu.png', 'image/xiaojiao.png','image/weijiao.png','image/yuwei.png'];
        var userSigns = ['wo','xiang','shui','jiao','jiao','~~~~'];
        randomAdd(userNames,userIcons,userSigns);
        //clickMark2Pixel();
        createPointMarker();
        manageControl();
        geocoder = new GClientGeocoder();
		
    }
}

//clickMap to pixel
function clickMark2Pixel(){
    var userIcon = new GIcon(G_DEFAULT_ICON);
    userIcon.image = 'image/run.gif';
    GEvent.addListener(map,"click", function(overlay,latlng) {
        markerOptions ={
            icon:userIcon,
            draggable: true
        }
        var marker = new GMarker(latlng,markerOptions);
        GEvent.addListener(marker,"click", function() {
            var myHtml = "The GLatLng value is: " + marker.getLatLng() + " at zoom level " + map.getZoom();
            map.openInfoWindow(latlng, myHtml);
        });
        map.addOverlay(marker);
    });
}

//add manageControl tool map
function manageControl(){
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
}

//gecoder show address	
function showAddress(address) {
    if (geocoder) {
        geocoder.getLatLng(
            address,
            function(point) {
                if (!point) {
                    alert(address + " not found");
                } else {
                    map.setCenter(point, 13);
                    var marker = new GMarker(point);
                    map.addOverlay(marker);
                    marker.openInfoWindowHtml(address);
                }
            }
            );
    }
}

//add user randomly
function randomAdd(userNames,userIcons,userSigns){
    // Add 10 markers to the map at random locations
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
        
    for (var i = 0; i < userNames.length; i++) {
        var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
            southWest.lng() + lngSpan * Math.random());
        addUser(userNames[i],point,userIcons[i],userSigns[i]);
    }
}

//add a User to map
function addUser(name,position,imageIcon,clickedMsg){
    // Create our "tiny" marker icon
    var userIcon = new GIcon(G_DEFAULT_ICON);
    userIcon.image = imageIcon;
    // Set up our GMarkerOptions object
    markerOptions = {
        icon:userIcon,
        draggable: true
    };
        
    var dragableMarker = new GMarker(position, markerOptions);

    GEvent.addListener(dragableMarker , "dragstart", function() {
        map.closeInfoWindow();
    });

    GEvent.addListener(dragableMarker , "dragend", function() {
        var infoHtml = '<b>'+name+'</b><br/>'+'position:'+ '<br/>'+ dragableMarker.getLatLng().y + '<br/>' + dragableMarker.getLatLng().x;
        dragableMarker.openInfoWindowHtml(infoHtml);
    });
    
    GEvent.addListener(dragableMarker,"click", function() {
        map.openInfoWindow(dragableMarker.getLatLng(), clickedMsg);
    });
    map.addOverlay(dragableMarker);
}

//create a point marker
function createPointMarker() {
    var userIcon = new GIcon(G_DEFAULT_ICON);
    userIcon.image = 'image/run.gif';
    GEvent.addListener(map,"click", function(overlay,latlng) {
        markerOptions ={
            icon:userIcon,
            draggable: true
        }
        var marker = new GMarker(latlng,markerOptions);

        //click action
        GEvent.addListener(marker,"click", function() {
            var myHtml = "The GLatLng value is: " + marker.getLatLng() + " at zoom level " + map.getZoom();
            map.openInfoWindow(marker.getLatLng(), myHtml);
            highlighted_marker = marker;
        });

        //drag action
        GEvent.addListener(marker,"drag", function() {
            createEncodings();
        });
        point_markers.push(marker);
        createEncodings();
        map.addOverlay(marker);
    });
}

// Returns the index of the marker in the polyline.
function findMarkerIndex(point_marker) {
    var index = -1;
    for (var  i = 0; i < point_markers.length; ++i) {
        if (point_markers[i] == point_marker) {
            index = i;
            break;
        }
    }
    return index;
}

//Delete a mark
function deleteMark(){
    if(highlighted_marker==null){
        alert('not select a point');
        return;
    }
    if (point_markers.length > 0) {
        var point_index = findMarkerIndex(highlighted_marker);

        if (point_index >= 0 && point_index < point_markers.length) {

            if (highlighted_marker == point_markers[point_index]) {
                highlighted_marker = null;
            }

            map.removeOverlay(point_markers[point_index]);
            point_markers.splice(point_index, 1);
            createEncodings();
        }

        if (point_markers.length > 0) {
            if (point_markers == 0) {
                point_markers++;
            }
            highlighted_marker = point_markers[point_index-1];
        }
    }
}

// Create the encoded polyline and level strings
function createEncodings() {
    var i = 0;
	
    var plat = 0;
    var plng = 0;

    var encoded_points = "";
    var encoded_levels = "BB";

    for(i = 0; i < point_markers.length; i++) {
        var point = point_markers[i].getLatLng();
        var lat = point.lat();
        var lng = point.lng();

        var late5 = Math.round(lat * 1e5);
        var lnge5 = Math.round(lng * 1e5);

        dlat = late5 - plat;
        dlng = lnge5 - plng;

        plat = late5;
        plng = lnge5;

        encoded_points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
    }

    if (polyline) {
        map.removeOverlay(polyline);
    }

    if (point_markers.length > 1) {
        polyline = GPolyline.fromEncoded({
            color: "#0000FF",
            weight: 10,
            points: encoded_points,
            zoomFactor: 32,
            levels: encoded_levels,
            numLevels: 4
        });

        map.addOverlay(polyline);
    }
}

// Encode a signed number in the encode format.
function encodeSignedNumber(num) {
    var sgn_num = num << 1;

    if (num < 0) {
        sgn_num = ~(sgn_num);
    }

    return(encodeNumber(sgn_num));
}

// Encode an unsigned number in the encode format.
function encodeNumber(num) {
    var encodeString = "";

    while (num >= 0x20) {
        encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
        num >>= 5;
    }

    encodeString += (String.fromCharCode(num + 63));
    return encodeString;
}


function getAddress(overlay, latlng) {
    if (latlng != null) {
        address = latlng;
        geocoder.getLocations(latlng, showAddress2);
    }
}

function directionAnalysis(response){
    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        directionsPanel = document.getElementById("route");
        directions = new GDirections(map, directionsPanel);
        var from;
        var to;
        var roadsearch ="from:"+ from +"to:"+to;
        directions.load(roadsearch);
    }
}


function showAddress2(response) {
    map.clearOverlays();
    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
            place.Point.coordinates[0]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(
            '<b>orig latlng:</b>' + response.name + '<br/>' +
            '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
            '<b>Status Code:</b>' + response.Status.code + '<br>' +
            '<b>Status Request:</b>' + response.Status.request + '<br>' +
            '<b>Address:</b>' + place.address + '<br>' +
            '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
            '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
    }
}​